/**
 * TODO <br>
 * 0.2: weijj:2019年5月10日 下午4:19:38:TODO <br>
 * @author  weijj
 * @since 2019年5月10日 下午4:19:38
 * @date 2019年5月10日 下午4:19:38
 * @version 0.1 初始为0.1,后续变更则修改
 */
package com.fdb.efp.batch.service.impl.dw;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Service;

import com.fdb.basic.framework.core.constant.MonAlrmLvlEnums.MonAlrmLvlEnum;
import com.fdb.basic.framework.core.util.DateTool;
import com.fdb.efp.batch.common.constant.BdLoanConstant;
import com.fdb.efp.batch.service.domain.TxtFileLoadBean;
import com.fdb.efp.batch.service.domain.dw.DwBaiduOpenBean;
import com.fdb.efp.batch.service.facade.dw.DwBaiduOpenBatchService;
import com.fdb.efp.batch.service.util.DueDataUtil;
import com.fdb.efp.batch.service.util.SDicMappingUtil;
import com.fdb.efp.batch.service.util.TxtFileLoadPlugin;
import com.fdb.efp.loan.service.facade.AccoutErroTempService;
import com.fdb.efp.loan.service.facade.DwBaiduOpenTempService;
import com.fdb.efp.loan.service.vo.AccoutErroTempVO;
import com.fdb.efp.nls.service.facade.BdLoanpayService;
import com.fdb.efp.nls.service.vo.BdLoanpayVO;

/**
 * 根据百度同步过来的贷款每日放款明细临时表数据修改放款申请信息表
 * 
 * @author weijj
 * @since 2019年5月10日 下午4:19:38
 * @version 1.0
 */
@Service("dwBaiduOpenBatchService")
public class DwBaiduOpenBatchServiceImpl implements DwBaiduOpenBatchService {

	private static Logger logger = LoggerFactory.getLogger(DwBaiduOpenBatchServiceImpl.class);

	@Autowired
	@Qualifier("bdLoanpayService")
	private BdLoanpayService bdLoanpayService;// 放款申请信息表

	@Autowired
	@Qualifier("dwBaiduOpenTempService")
	private DwBaiduOpenTempService dwBaiduOpenTempService;// 贷款每日放款明细临时信息

	@Autowired
	@Qualifier("accoutErroTempService")
	private AccoutErroTempService accoutErroTempService;// 错误信息

	// /**
	// * 根据百度同步过来的贷款每日放款明细临时表数据修改放款申请信息表 <br>
	// * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	// *
	// * @author weijj
	// * @since 2019年5月7日 下午3:02:37
	// * @date 2019年5月7日 下午3:02:37
	// * @version 0.1
	// */
	// @Override
	// public boolean batchUpdateDwBaiduOpen() throws Exception {
	// // TODO Auto-generated method stub
	// boolean result = false;
	// long startTime = System.currentTimeMillis();
	// logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表：[" + DateTool.formatDate(new
	// Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
	// // 可以配置参数
	// Integer pageSize = 1000;
	// try {
	// // 需要新增或者修改的 放款申请信息
	// List<BdLoanpayVO> list = null;
	// // 分页信息
	// DwBaiduOpenTempVO pageInfo = new DwBaiduOpenTempVO();
	// // 新增或者修改的 放款申请信息
	// int num = 0;
	// // 页数
	// int page = 1;
	// // pageSize初始化
	// if (pageSize > 0) {
	// pageInfo.setSize(pageSize);
	// } else {
	// pageInfo.setSize(1000);
	// }
	// // 单位转换
	// final int oneHundred100 = 100;
	// final String createUser = "admin";
	// // 判断循环次数
	// int size = dwBaiduOpenTempService.queryCount();
	// String size_msg = "【放款申请信息表】数据量：" + size;
	// logger.info(size_msg, "message{}");
	// int loopCount = (size / pageInfo.getSize()) + 1;
	// // 授信申请信息
	// // BdSxapplyTempVO inBdSxapplyTempVO = new BdSxapplyTempVO();
	// for (int i = 0; i < loopCount; i++) {
	// // 分页查询【放款申请信息表】数据
	// List<DwBaiduOpenTempVO> tempList =
	// dwBaiduOpenTempService.queryByPage(pageInfo);
	// list = new ArrayList<BdLoanpayVO>();
	// if (tempList != null && !tempList.isEmpty()) {
	// for (DwBaiduOpenTempVO dwBaiduOpenTempVO : tempList) {
	// // 放款申请信息
	// BdLoanpayVO bdLoanpayVO = new BdLoanpayVO();
	// bdLoanpayVO.setApplySeq(dwBaiduOpenTempVO.getSeqNo());
	// bdLoanpayVO.setCusName(dwBaiduOpenTempVO.getCustName());
	// bdLoanpayVO.setLoanCcy(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.CURRENCY,
	// dwBaiduOpenTempVO.getCurrency()));
	// // cont_start_date char(10) Y 起始日
	// bdLoanpayVO.setContStartDate(DueDataUtil.dateInfoTrans(dwBaiduOpenTempVO.getStartDate()));
	// bdLoanpayVO.setContEndDate(DueDataUtil.dateInfoTrans(dwBaiduOpenTempVO.getEndDate()));
	// bdLoanpayVO.setDnSts(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.DN_STS,
	// dwBaiduOpenTempVO.getFundStatus()));
	// bdLoanpayVO.setCreateUser(createUser);
	// bdLoanpayVO.setCreateTime(DueDataUtil.formatDateTime10To19(dwBaiduOpenTempVO.getEtlDate()));
	// bdLoanpayVO.setLastModifyUser(createUser);
	// bdLoanpayVO.setLastModifyTime(DateTool.getCurrentDateTime());
	// bdLoanpayVO.setOrderId(dwBaiduOpenTempVO.getOrderId());
	// bdLoanpayVO.setCurDate(DueDataUtil.dateInfoTrans(dwBaiduOpenTempVO.getCurDate()));
	// bdLoanpayVO.setLeader(dwBaiduOpenTempVO.getLeader());
	// bdLoanpayVO.setPartner(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE,
	// dwBaiduOpenTempVO.getParter()));
	// bdLoanpayVO
	// .setCertType(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.CERT_TYPE,
	// dwBaiduOpenTempVO.getCertType()));
	// bdLoanpayVO.setCertNo(dwBaiduOpenTempVO.getCertNo());
	// bdLoanpayVO.setLoanId(dwBaiduOpenTempVO.getLoanId());
	// bdLoanpayVO.setApplyDate(DueDataUtil.dateInfoTrans(dwBaiduOpenTempVO.getApplyDate()));
	// bdLoanpayVO.setStartDate(DueDataUtil.dateInfoTrans(dwBaiduOpenTempVO.getStartDate()));
	// // repay_mode 还款方式
	// bdLoanpayVO.setRepayMode(
	// SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.REPAY_MODE,
	// dwBaiduOpenTempVO.getRepayMode()));
	// bdLoanpayVO.setRepayCycle(dwBaiduOpenTempVO.getRepayCycle());
	// bdLoanpayVO.setTotalTerms(dwBaiduOpenTempVO.getTotalTerms().toString());
	// bdLoanpayVO.setGraceDay(dwBaiduOpenTempVO.getGraceDay().toString());
	// bdLoanpayVO.setEncashAmt(DueDataUtil.checkDecimalInfo(dwBaiduOpenTempVO.getEncashAmt(),
	// oneHundred100));
	// list.add(bdLoanpayVO);
	// }
	// // 需要新增或者更新的放款申请信息
	// if (list != null && !list.isEmpty()) {
	// int updateSize = bdLoanpayService.insertOrUpdateBdLoanpay(list);
	// num += updateSize;
	// }
	// }
	// pageInfo.setPage(++page);
	// }
	// String num_msg = "【放款申请信息表】插入或更新数据处理结果:" + num;
	// logger.info(num_msg, "message{}");
	// result = true;
	// } catch (Exception e) {
	// e.printStackTrace();
	// String tableName = "bd_loanpay";
	// String errorMsg = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错";
	// String remark = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错，错误信息：" + e.getMessage();
	// addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg,
	// remark);
	// logger.error(remark);
	// throw new Exception(remark);
	// }
	// long endTime = System.currentTimeMillis();
	// logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表：[" + DateTool.formatDate(new
	// Date(endTime), DateTool.PATTERN_DATETIME) + "]， 处理结束");
	// logger.info("SERIOUS，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" +
	// result + "]");
	// return result;
	// }

	/**
	 * 根据百度同步过来的贷款每日放款明细临时表数据修改放款申请信息表 <br>
	 * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 下午3:02:37
	 * @date 2019年5月7日 下午3:02:37
	 * @version 0.1
	 */
	@Override
	public boolean batchUpdateDwBaiduOpen(String fileUrl) throws Exception {
		// 处理结果
		boolean result = false;
		long startTime = System.currentTimeMillis();
		logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表：[" + DateTool.formatDate(new Date(startTime), DateTool.PATTERN_DATETIME) + "]， 处理开始");
		try {
			TxtFileLoadPlugin txtFileLoadPlugin = new TxtFileLoadPlugin(fileUrl, "\u0002", "UTF-8", 0, 1000);
			List<TxtFileLoadBean> txtFileLoadList = txtFileLoadPlugin.run(new DwBaiduOpenBean());
			result = dueData(txtFileLoadList);
			if (txtFileLoadList.size() != 0) {
				while (!txtFileLoadList.get(txtFileLoadList.size() - 1).isReadedComplete) {
					txtFileLoadPlugin.setFirstRead(false);
					txtFileLoadList = txtFileLoadPlugin.run(new DwBaiduOpenBean());
					if (txtFileLoadList.size() == 0) {
						break;
					}
					result = dueData(txtFileLoadList);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "bd_loanpay";
			String errorMsg = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错";
			String remark = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
			throw new Exception(remark);
		}
		long endTime = System.currentTimeMillis();
		logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表：[" + DateTool.formatDate(new Date(endTime), DateTool.PATTERN_DATETIME) + "]， 处理结束");
		logger.info("SERIOUS，耗时：[" + (endTime - startTime) / 1000.0 + "]秒，处理结果[" + result + "]");
		return result;
	}

	/**
	 * 根据百度同步过来的贷款每日放款明细文件数据加工初始化放款申请信息<br>
	 * 0.1: weijj:2019年5月7日 下午3:02:37:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 下午3:02:37
	 * @date 2019年5月7日 下午3:02:37
	 * @version 0.1
	 */
	public boolean dueData(List<TxtFileLoadBean> txtFileLoadList) {
		logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表加工处理开始！");
		// 需要新增或者修改的 放款申请信息
		List<BdLoanpayVO> list = new ArrayList<BdLoanpayVO>();
		// 处理结果
		boolean result = false;
		// 新增或者修改的数量
		int num = 0;
		// 单位转换
		final int oneHundred100 = 100;
		// 创建、修改用户
		final String createUser = "admin";
		DwBaiduOpenBean dwBaiduOpenBean = new DwBaiduOpenBean();
		try {
			for (int i = 0; i < txtFileLoadList.size(); i++) {
				dwBaiduOpenBean = (DwBaiduOpenBean) txtFileLoadList.get(i);
				// 放款申请信息
				BdLoanpayVO bdLoanpayVO = new BdLoanpayVO();
				bdLoanpayVO.setApplySeq(dwBaiduOpenBean.getSeqNo());
				bdLoanpayVO.setCusName(dwBaiduOpenBean.getCustName());
				bdLoanpayVO.setLoanCcy(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.CURRENCY, dwBaiduOpenBean.getCurrency()));
				// cont_start_date char(10) Y 起始日
				bdLoanpayVO.setContStartDate(DueDataUtil.dateInfoTrans(dwBaiduOpenBean.getStartDate()));
				bdLoanpayVO.setContEndDate(DueDataUtil.dateInfoTrans(dwBaiduOpenBean.getEndDate()));
				bdLoanpayVO.setDnSts(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.DN_STS, dwBaiduOpenBean.getFundStatus()));
				bdLoanpayVO.setCreateUser(createUser);
				bdLoanpayVO.setCreateTime(DueDataUtil.formatDateTime10To19(dwBaiduOpenBean.getEtlDate()));
				bdLoanpayVO.setLastModifyUser(createUser);
				bdLoanpayVO.setLastModifyTime(DateTool.getCurrentDateTime());
				bdLoanpayVO.setOrderId(dwBaiduOpenBean.getOrderId());
				bdLoanpayVO.setCurDate(DueDataUtil.dateInfoTrans(dwBaiduOpenBean.getCurDate()));
				bdLoanpayVO.setLeader(dwBaiduOpenBean.getLeader());
				bdLoanpayVO.setPartner(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.PRD_CODE, dwBaiduOpenBean.getParter()));
				bdLoanpayVO.setCertType(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.CERT_TYPE, dwBaiduOpenBean.getCertType()));
				bdLoanpayVO.setCertNo(dwBaiduOpenBean.getCertNo());
				bdLoanpayVO.setLoanId(dwBaiduOpenBean.getLoanId());
				bdLoanpayVO.setApplyDate(DueDataUtil.dateInfoTrans(dwBaiduOpenBean.getApplyDate()));
				bdLoanpayVO.setStartDate(DueDataUtil.dateInfoTrans(dwBaiduOpenBean.getStartDate()));
				// repay_mode 还款方式
				bdLoanpayVO.setRepayMode(SDicMappingUtil.getLocalSysDicVal(BdLoanConstant.REPAY_MODE, dwBaiduOpenBean.getRepayMode()));
				bdLoanpayVO.setRepayCycle(dwBaiduOpenBean.getRepayCycle());
				bdLoanpayVO.setTotalTerms(dwBaiduOpenBean.getTotalTerms().toString());
				bdLoanpayVO.setGraceDay(dwBaiduOpenBean.getGraceDay().toString());
				bdLoanpayVO.setEncashAmt(DueDataUtil.checkDecimalInfo(dwBaiduOpenBean.getEncashAmt(), oneHundred100));
				bdLoanpayVO.setFailType(dwBaiduOpenBean.getFailType());
				bdLoanpayVO.setCardNo(dwBaiduOpenBean.getCardNo());
				list.add(bdLoanpayVO);
			}
			if (list != null && !list.isEmpty()) {
				num = bdLoanpayService.insertOrUpdateBdLoanpay(list);
			}
			String num_msg = "【放款申请信息表】插入或更新数据处理结果:" + num;
			logger.info(num_msg, "message{}");
			if (num > 0) {
				result = true;
			}
		} catch (Exception e) {
			e.printStackTrace();
			String tableName = "bd_loanpay";
			String errorMsg = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错";
			String remark = "同步过来的贷款每日放款明细临时表数据修改放款申请信息表出错，错误信息：" + e.getMessage();
			addErrorInfo(tableName, MonAlrmLvlEnum.SERIOUS.getEnname(), errorMsg, remark);
			logger.error(remark);
		} finally {
			// 清空信息
			list = null;
			txtFileLoadList = null;
		}
		logger.info("同步过来的贷款每日放款明细临时表数据修改放款申请信息表加工处理结束！");
		return result;
	}

	/**
	 * 
	 * 记录异常信息 <br>
	 * 0.1:weijj:2019年5月7日 上午11:31:23:新增 <br>
	 * 
	 * @author weijj
	 * @since 2019年5月7日 上午11:31:23
	 * @date 2019年5月7日 上午11:31:23
	 * @version 0.1
	 */
	private void addErrorInfo(String tableName, String errorType, String errorMsg, String remark) {
		AccoutErroTempVO accoutErroTempVO = new AccoutErroTempVO();
		// 表名
		accoutErroTempVO.setTableName(tableName);
		// 错误级别
		accoutErroTempVO.setErroType(errorType);
		// 错误信息
		accoutErroTempVO.setErroMsg(errorMsg);
		// 备注
		accoutErroTempVO.setRemark(remark);
		// 创建时间
		accoutErroTempVO.setCreateData(DateTool.getCurrentDateTime());
		// 修改时间
		accoutErroTempVO.setLastModifyTime(DateTool.getCurrentDateTime());
		// 记录异常信息
		accoutErroTempService.insert(accoutErroTempVO);
	}
}
